package com.xxx.lease.common.utils;

import com.xxx.lease.common.exception.LeaseException;
import com.xxx.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;


import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {

    private static long tokenExpiration = 6000000 * 60 * 1000L;

    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    public static String createToken(Long userId, String userName) {

        String token = Jwts.builder().setSubject("USER_INFO").setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                claim("userId", userId).claim("userName", userName).
                signWith(tokenSignKey).compressWith(CompressionCodecs.GZIP).
                compact();

        return token;
    }

    public static Claims parseToken(String token) throws LeaseException {

        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(tokenSignKey).build().parseClaimsJws(token);

            return claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

}
